package nsn.message.aggragtor.feeds;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import nsn.message.aggragtor.feeds.exceptions.EntryFeedException;
import nsn.message.aggregator.model.AbstractSourceType;
import nsn.message.aggregator.model.ISource;

import com.sun.syndication.fetcher.FeedFetcher;

/**
 * http://www.sr.se/rssfeed/rssfeed.aspx?Poddfeed=4019
 * http://lifehacker.com/index.xml
 * http://www.facebook.com/feeds/notifications.php
 * ?id=549006760&viewer=549006760&key=9aa3ec133f&format=rss20
 * http://www.markshuttleworth.com/feed http://n8tip.com/feed
 * http://www.podcasternews.com/feeds/enbr.xml
 * http://sensualjava.blogspot.com/feeds/posts/default?alt=rss
 * 
 * @author Lukasz Nowak
 * @since 10-03-2011
 * 
 */
public class SourceTypeFeed extends AbstractSourceType {

	/**
	 * 
	 */
	static public final String URL = "URL";

	/**
     * 
     */
	static private final long serialVersionUID = -2640720915386657755L;

	static private final String[] PARAMS = { URL };

	private final transient FeedFetcher _feedFetcher;

	/**
	 * 
	 */
	public SourceTypeFeed() {
		_feedFetcher = FeedFetcherService.getFeedFetcher();

		setName("Feeds (RSS, ATOM)");
	}

	@Override
	public ISource create(final Map<String, String> params) {
		final String urlName = params.get(URL);
		if (urlName == null) {
			return null;
		}

		try {
			final URL url = new URL(urlName);
			final SourceFeed source = new SourceFeed(this, url);
			getSources().add(source);
			source.addPropertyChangeListener(new PropertyChangeListener() {

				@Override
				public void propertyChange(PropertyChangeEvent event) {
					propertyChangeSupport.firePropertyChange(event);
				}
			});
			propertyChangeSupport.firePropertyChange("SourceCreated", null,
					source);

			return source;
		} catch (final MalformedURLException e) {
			throw new EntryFeedException(e);
		} catch (final IllegalArgumentException e) {
			throw new EntryFeedException(e);
		}

	}

	@Override
	public String[] parameters() {
		return PARAMS;
	}

	/**
	 * 
	 * 
	 * @return FeedFetcher
	 */
	protected FeedFetcher getFeedFetcher() {
		return _feedFetcher;
	}

	@Override
	public void update() {
		for (final ISource source : getSources()) {
			source.update();
		}
	}

}
